package com.ctz.commonframe.ui.view;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.TextView;

import com.ctz.commonframe.R;
import com.ctz.commonframe.utils.VoiceRecorder;



/**
 * Created by 陈堂正 on 2017/2/23.
 */

public class VoiceButton extends TextView {
    private static final int DEFAULT_MIC_MAX_LEVEL = 7;
    private static final int UPDATE_MIC_LEVEL_INTERVAL = 500;
    private static final int MIN_VOICE_DURATION = 1000;

    private VoiceRecorder recorder;
    private VoiceButtonState state;
    private OnVoiceRecorderListener listener;
    private Handler handler = new Handler();
    private Runnable updateMicLevelRunnable = new Runnable() {
        @Override
        public void run() {
            updateMicLevel();
        }
    };

    public VoiceButton(Context context) {
        super(context);
        init();
    }

    public VoiceButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void setOnVoiceRecorderListener(OnVoiceRecorderListener listener) {
        this.listener = listener;
    }

    private void init(){
        recorder = new VoiceRecorder(getContext());
        onState(VoiceButtonState.NORMAL);
    }

    private void updateMicLevel(){
        if(recorder != null && recorder.isStarted()){
            int level = recorder.getMicLevel(DEFAULT_MIC_MAX_LEVEL);
            listener.onMicLevelChanged(level);
            handler.postDelayed(updateMicLevelRunnable, UPDATE_MIC_LEVEL_INTERVAL);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                onState(VoiceButtonState.RECORDING);
                if(recorder.start()){
                    if(listener != null) {
                        listener.onStarted();
                        updateMicLevel();
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if(recorder != null && recorder.isStarted()) {
                    if (isCancelRecorder(x, y)) {
                        onState(VoiceButtonState.WANT_TO_CANCEL);
                    } else {
                        onState(VoiceButtonState.RECORDING);
                    }
                }
                break;

            case MotionEvent.ACTION_UP:
                if(recorder != null && recorder.isStarted()){
                    //正常录音结束，时间少于1秒则认为太短，删除文件
                    if(state == VoiceButtonState.RECORDING){
                        long duration = recorder.stop();
                        if(listener != null){
                            if(duration < MIN_VOICE_DURATION){
                                recorder.deleteFile();
                                listener.onTooShort();
                            }else{
                                listener.onFinish(duration, recorder.getVoiceFilePath());
                            }
                        }
                    }else if(state == VoiceButtonState.WANT_TO_CANCEL){
                        recorder.stop();
                        recorder.deleteFile();
                        if(listener != null){
                            listener.onCanceled();
                        }
                    }
                }
                onState(VoiceButtonState.NORMAL);
                break;
        }
        return super.onTouchEvent(event);
    }

    /**
     * 根据不同状态，更改不同的文字和显示的背景
     */
    private void onState(VoiceButtonState state) {
        this.state = state;
        setText(state.getText());
        switch (state) {
            case NORMAL:
                setBackgroundResource(R.drawable.bg_white_corner8);
                break;
            case RECORDING:
                setBackgroundResource(R.drawable.bg_blue_corner8);
                break;
            case WANT_TO_CANCEL:
                break;
        }
    }

    /**
     * 根据移动后的位置，判断是否取消录音
     */
    private boolean isCancelRecorder(int x, int y) {
        if (x < 0 || x > getWidth() || y < 0 || y > getHeight()) {
            return true;
        }
        return false;
    }

    /**
     * 录音过程回调接口
     */
    public interface OnVoiceRecorderListener {
        void onStarted();
        void onMicLevelChanged(int level);
        void onCanceled();
        void onTooShort();
        void onFinish(long time, String filePath);
    }

    private enum VoiceButtonState{
        NORMAL("按住说话"), RECORDING("松开结束"), WANT_TO_CANCEL("松开手指 取消发送");
        private String text;

        VoiceButtonState(String text){
            this.text = text;
        }

        public void setText(String text){
            this.text = text;
        }

        public String getText(){
            return text;
        }
    }


}
